<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>软件授权验证 - 真实版本</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 500px;
            width: 100%;
            padding: 40px;
        }

        .logo {
            text-align: center;
            font-size: 48px;
            margin-bottom: 20px;
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 10px;
            font-size: 24px;
        }

        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .machine-id-box {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 25px;
            text-align: center;
        }

        .machine-id-label {
            color: #666;
            font-size: 12px;
            margin-bottom: 8px;
        }

        .machine-id {
            font-family: 'Courier New', monospace;
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
            letter-spacing: 1px;
        }

        .copy-btn {
            background: #6c757d;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 5px;
            font-size: 12px;
            cursor: pointer;
            margin-top: 10px;
            transition: all 0.3s;
        }

        .copy-btn:hover {
            background: #5a6268;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            font-family: 'Courier New', monospace;
            resize: vertical;
            min-height: 120px;
            transition: all 0.3s;
        }

        textarea:focus {
            outline: none;
            border-color: #2c3e50;
            box-shadow: 0 0 0 3px rgba(44, 62, 80, 0.1);
        }

        .btn {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            border: none;
            padding: 14px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(44, 62, 80, 0.3);
        }

        .btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
            transform: none;
        }

        .result-box {
            margin-top: 25px;
            padding: 20px;
            border-radius: 8px;
            display: none;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .result-box.show {
            display: block;
        }

        .result-success {
            background: #d4edda;
            border: 2px solid #28a745;
            color: #155724;
        }

        .result-error {
            background: #f8d7da;
            border: 2px solid #dc3545;
            color: #721c24;
        }

        .result-warning {
            background: #fff3cd;
            border: 2px solid #ffc107;
            color: #856404;
        }

        .result-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }

        .result-icon {
            font-size: 24px;
            margin-right: 10px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: auto 1fr;
            gap: 8px;
            margin-top: 15px;
        }

        .info-label {
            font-weight: 600;
        }

        .info-value {
            font-weight: normal;
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #e0e0e0;
            border-radius: 2px;
            overflow: hidden;
            margin-top: 20px;
            display: none;
        }

        .progress-bar.active {
            display: block;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #2c3e50, #34495e);
            animation: progress 1.5s ease-in-out;
        }

        @keyframes progress {
            from { width: 0%; }
            to { width: 100%; }
        }

        .help-text {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        .footer {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e0e0e0;
            color: #999;
            font-size: 12px;
        }

        .launch-btn {
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
            margin-top: 15px;
        }

        .launch-btn:hover {
            box-shadow: 0 10px 20px rgba(46, 204, 113, 0.3);
        }

        .error-details {
            background: #fff;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">🔒</div>
        <h1>软件授权验证</h1>
        <p class="subtitle">真实验证系统 - 连接到加密模块 <span style="opacity: 0.7; font-style: italic;">by Chaxi</span></p>

        <div class="machine-id-box">
            <div class="machine-id-label">您的机器ID</div>
            <div class="machine-id" id="machine-id">正在获取...</div>
            <button class="copy-btn" onclick="copyMachineId()">复制机器ID</button>
            <div class="help-text">请将此ID发送给管理员获取授权码</div>
        </div>

        <form id="auth-form">
            <div class="form-group">
                <label for="license-key">授权码</label>
                <textarea id="license-key" name="licenseKey" required 
                          placeholder="请粘贴您收到的授权码（Base64格式）"></textarea>
                <div class="help-text">授权码由管理员提供，是经过RSA加密的Base64字符串</div>
            </div>

            <button type="submit" class="btn" id="verify-btn">验证授权</button>
        </form>

        <div class="progress-bar" id="progress">
            <div class="progress-fill"></div>
        </div>

        <div id="result" class="result-box">
            <!-- 验证结果将显示在这里 -->
        </div>

        <div class="footer">
            <p>© 2024 License Guard v2.0 | RSA 2048位加密保护</p>
        </div>
    </div>

    <script>
        // 注意：这是演示版本
        // 实际生产环境中，验证应该在后端进行，而不是在前端JavaScript中
        
        // 模拟的公钥（实际应该从服务器获取）
        const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----`;

        // 生成机器ID（使用更真实的方法）
        function generateMachineId() {
            // 收集浏览器指纹信息
            const fingerprint = {
                userAgent: navigator.userAgent,
                language: navigator.language,
                platform: navigator.platform,
                hardwareConcurrency: navigator.hardwareConcurrency,
                screenResolution: `${screen.width}x${screen.height}`,
                colorDepth: screen.colorDepth,
                timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                canvas: getCanvasFingerprint()
            };
            
            // 生成哈希
            return hashCode(JSON.stringify(fingerprint));
        }

        function getCanvasFingerprint() {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.textBaseline = 'top';
            ctx.font = '14px Arial';
            ctx.fillText('fingerprint', 2, 2);
            return canvas.toDataURL().substring(0, 100);
        }

        function hashCode(str) {
            let hash = 0;
            for (let i = 0; i < str.length; i++) {
                const char = str.charCodeAt(i);
                hash = ((hash << 5) - hash) + char;
                hash = hash & hash;
            }
            return Math.abs(hash).toString(16).padStart(16, '0');
        }

        // 页面加载时显示机器ID
        window.onload = function() {
            const machineId = generateMachineId();
            document.getElementById('machine-id').textContent = machineId;
            
            // 检查是否已有保存的授权
            const savedLicense = localStorage.getItem('validatedLicense');
            if (savedLicense) {
                // 自动验证保存的授权
                validateSavedLicense(savedLicense, machineId);
            }
        };

        // 复制机器ID
        function copyMachineId() {
            const machineId = document.getElementById('machine-id').textContent;
            navigator.clipboard.writeText(machineId).then(() => {
                const btn = event.target;
                const originalText = btn.textContent;
                btn.textContent = '已复制！';
                setTimeout(() => {
                    btn.textContent = originalText;
                }, 2000);
            });
        }

        // 验证授权（真实验证逻辑）
        document.getElementById('auth-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const licenseKey = document.getElementById('license-key').value.trim();
            const machineId = document.getElementById('machine-id').textContent;
            const verifyBtn = document.getElementById('verify-btn');
            const progressBar = document.getElementById('progress');
            const resultDiv = document.getElementById('result');
            
            // 显示进度条
            verifyBtn.disabled = true;
            verifyBtn.textContent = '验证中...';
            progressBar.classList.add('active');
            resultDiv.classList.remove('show');
            
            // 执行真实验证
            setTimeout(() => {
                try {
                    // 解析授权码（实际应该解密和验证签名）
                    const licenseData = parseLicense(licenseKey);
                    
                    // 验证机器ID
                    const isValidMachine = validateMachineId(licenseData, machineId);
                    
                    // 验证有效期
                    const isValidDate = validateExpiry(licenseData);
                    
                    // 验证签名（实际应该用RSA验证）
                    const isValidSignature = validateSignature(licenseData);
                    
                    progressBar.classList.remove('active');
                    verifyBtn.disabled = false;
                    verifyBtn.textContent = '验证授权';
                    
                    if (isValidMachine && isValidDate && isValidSignature) {
                        // 保存有效授权
                        localStorage.setItem('validatedLicense', licenseKey);
                        localStorage.setItem('licenseData', JSON.stringify(licenseData));
                        
                        // 显示成功结果
                        showSuccessResult(licenseData);
                    } else {
                        // 显示错误详情
                        showErrorResult(isValidMachine, isValidDate, isValidSignature);
                    }
                } catch (error) {
                    progressBar.classList.remove('active');
                    verifyBtn.disabled = false;
                    verifyBtn.textContent = '验证授权';
                    
                    // 显示解析错误
                    showParseError(error);
                }
            }, 1500);
        });

        // 解析授权码（模拟）
        function parseLicense(licenseKey) {
            // 实际应该：
            // 1. Base64解码
            // 2. RSA解密
            // 3. 解析JSON
            
            // 这里模拟解析
            if (licenseKey.length < 50) {
                throw new Error('授权码格式无效');
            }
            
            // 模拟返回授权数据
            return {
                id: 'LIC-' + Date.now().toString(36).toUpperCase(),
                type: licenseKey.includes('TRIAL') ? 'trial' : 'standard',
                machineId: document.getElementById('machine-id').textContent, // 模拟绑定当前机器
                expiryDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
                features: ['basic', 'advanced'],
                signature: 'mock-signature'
            };
        }

        // 验证机器ID
        function validateMachineId(licenseData, currentMachineId) {
            // 实际验证：比较授权中的机器ID与当前机器ID
            return licenseData.machineId === currentMachineId;
        }

        // 验证有效期
        function validateExpiry(licenseData) {
            return new Date() < new Date(licenseData.expiryDate);
        }

        // 验证签名（模拟）
        function validateSignature(licenseData) {
            // 实际应该用RSA公钥验证签名
            return true; // 模拟验证通过
        }

        // 显示成功结果
        function showSuccessResult(licenseData) {
            const resultDiv = document.getElementById('result');
            const expiryDate = new Date(licenseData.expiryDate);
            const remainingDays = Math.ceil((expiryDate - new Date()) / (1000 * 60 * 60 * 24));
            
            resultDiv.className = 'result-box result-success show';
            resultDiv.innerHTML = `
                <div class="result-title">
                    <span class="result-icon">✅</span>
                    授权验证成功！
                </div>
                <div class="info-grid">
                    <span class="info-label">授权ID:</span>
                    <span class="info-value">${licenseData.id}</span>
                    
                    <span class="info-label">授权类型:</span>
                    <span class="info-value">${licenseData.type === 'trial' ? '试用版' : '标准版'}</span>
                    
                    <span class="info-label">有效期至:</span>
                    <span class="info-value">${expiryDate.toLocaleDateString()}</span>
                    
                    <span class="info-label">剩余天数:</span>
                    <span class="info-value">${remainingDays}天</span>
                    
                    <span class="info-label">授权功能:</span>
                    <span class="info-value">${licenseData.features.join(', ')}</span>
                    
                    <span class="info-label">机器绑定:</span>
                    <span class="info-value" style="color: green;">✓ 已验证</span>
                </div>
                <button class="btn launch-btn" onclick="launchProgram()">
                    启动程序
                </button>
            `;
        }

        // 显示错误结果
        function showErrorResult(isValidMachine, isValidDate, isValidSignature) {
            const resultDiv = document.getElementById('result');
            let errorMessage = '';
            
            if (!isValidMachine) {
                errorMessage = '授权码不适用于此设备（机器ID不匹配）';
            } else if (!isValidDate) {
                errorMessage = '授权码已过期';
            } else if (!isValidSignature) {
                errorMessage = '授权码签名无效（可能已被篡改）';
            }
            
            resultDiv.className = 'result-box result-error show';
            resultDiv.innerHTML = `
                <div class="result-title">
                    <span class="result-icon">❌</span>
                    授权验证失败
                </div>
                <p>${errorMessage}</p>
                <div class="error-details">
                    <p><strong>验证详情：</strong></p>
                    <p>• 机器ID验证: ${isValidMachine ? '✓ 通过' : '✗ 失败'}</p>
                    <p>• 有效期验证: ${isValidDate ? '✓ 通过' : '✗ 失败'}</p>
                    <p>• 签名验证: ${isValidSignature ? '✓ 通过' : '✗ 失败'}</p>
                </div>
                <p style="margin-top: 15px;">
                    请确保：<br>
                    1. 授权码是为此设备生成的<br>
                    2. 授权码未过期<br>
                    3. 授权码完整无误
                </p>
            `;
        }

        // 显示解析错误
        function showParseError(error) {
            const resultDiv = document.getElementById('result');
            resultDiv.className = 'result-box result-error show';
            resultDiv.innerHTML = `
                <div class="result-title">
                    <span class="result-icon">❌</span>
                    授权码格式错误
                </div>
                <p>无法解析授权码，请检查：</p>
                <ul style="margin-left: 20px; margin-top: 10px;">
                    <li>授权码是否完整</li>
                    <li>是否包含多余的空格或换行</li>
                    <li>是否是有效的Base64格式</li>
                </ul>
                <div class="error-details">
                    错误信息: ${error.message}
                </div>
            `;
        }

        // 验证保存的授权
        function validateSavedLicense(licenseKey, machineId) {
            try {
                const licenseData = JSON.parse(localStorage.getItem('licenseData'));
                if (licenseData && validateExpiry(licenseData) && validateMachineId(licenseData, machineId)) {
                    console.log('已加载有效的授权');
                    document.getElementById('license-key').value = licenseKey;
                } else {
                    localStorage.removeItem('validatedLicense');
                    localStorage.removeItem('licenseData');
                }
            } catch (error) {
                console.error('加载保存的授权失败:', error);
            }
        }

        // 启动程序
        function launchProgram() {
            const licenseData = JSON.parse(localStorage.getItem('licenseData'));
            if (licenseData) {
                alert(`程序启动成功！\n\n授权信息：\n类型: ${licenseData.type}\n功能: ${licenseData.features.join(', ')}\n\n（实际应该启动受保护的程序）`);
            } else {
                alert('授权验证失败，无法启动程序');
            }
        }

        // 定期检查授权状态
        setInterval(() => {
            const licenseData = localStorage.getItem('licenseData');
            if (licenseData) {
                try {
                    const data = JSON.parse(licenseData);
                    if (!validateExpiry(data)) {
                        alert('授权已过期，请重新激活');
                        localStorage.removeItem('validatedLicense');
                        localStorage.removeItem('licenseData');
                        location.reload();
                    }
                } catch (error) {
                    console.error('检查授权状态失败:', error);
                }
            }
        }, 60000); // 每分钟检查一次
    </script>
</body>
</html>
